import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:xrenovation/utils/http.dart';
import 'package:xrenovation/utils/storage.dart';

class ContractorsApi {
  static Future<Map<String, dynamic>> addSkill(String name) async {
    final res = await Http.post('/contractor/skill/add', {'name': name});
    return res.data;
  }

  static Future<Map<String, dynamic>> deleteContractor(String id) async {
    final res = await Http.delete('/contractor/delete/$id', {});
    return res.data;
  }

  static Future<Map<String, dynamic>> getContractorList() async {
    final res = await Http.get('/contractor/list');
    return res.data;
  }

  static Future<Map<String, dynamic>> getContractorReviews(String id) async {
    final res = await Http.get('/contractor/reviews/$id');
    return res.data;
  }

  static Future<Map<String, dynamic>> getSkillList() async {
    final res = await Http.get('/contractor/skill/list');
    return res.data;
  }

  static Future<Map<String, dynamic>> updateContractor({
    required String url,
    required Map<String, dynamic> data,
    File? imageFile,
  }) async {
    try {
      // 创建 MultipartRequest
      final uri = Uri.parse('${Http.baseUrl}$url');
      final request = http.MultipartRequest('POST', uri);

      // 添加文本字段
      data.forEach((key, value) {
        if (value != null) {
          request.fields[key] = value.toString();
        }
      });

      // 添加图片文件（如果存在）
      if (imageFile != null) {
        final fileStream = http.ByteStream(imageFile.openRead());
        final length = await imageFile.length();

        final multipartFile = http.MultipartFile(
          'image',
          fileStream,
          length,
          filename: imageFile.path.split('/').last,
          contentType: MediaType('image', 'jpeg'), // 根据实际类型调整
        );

        request.files.add(multipartFile);
      }

      // 添加 headers（如 token）
      request.headers['satoken'] = await Storage.getToken() ?? '';

      // 发送请求
      final response = await request.send();
      final responseData = await response.stream.bytesToString();

      return {
        'code': response.statusCode,
        'data': responseData.isNotEmpty ? json.decode(responseData) : null,
        'message': response.reasonPhrase ?? 'Request completed',
      };
    } catch (e) {
      return {'code': 500, 'message': e.toString()};
    }
  }
}
